package com.mxx.democharts2.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mxx.democharts2.dao.mapper.SmartProcessTaskMapper;
import com.mxx.democharts2.dao.mapper.SmartProductMapper;
import com.mxx.democharts2.dao.mapper.YuancheMapper;
import com.mxx.democharts2.dto.YuancheDto;
import com.mxx.democharts2.pojo.SmartProcessTaskExample;
import com.mxx.democharts2.pojo.SmartProduct;
import com.mxx.democharts2.pojo.SmartProductExample;
import com.mxx.democharts2.service.YuancheService;
import com.mxx.democharts2.utils.DateUtils;
import com.mxx.democharts2.utils.PageQuery;
import com.mxx.democharts2.vo.YuancheQuery;
import com.mxx.democharts2.vo.YuancheVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class YuancheServiceImpl implements YuancheService {

    @Autowired
    private YuancheMapper yuancheMapper;
    @Autowired
    private SmartProcessTaskMapper smartProcessTaskMapper;
    /**
     * 计算上月的主齿钳工废次品总数
     * @return "product_new_code", "yuanche_waste_count"
     */
    /*private Map<String, Integer> getYuancheWasteCount(Date start, Date end) {
        List<Map<String, Object>> taskWasteList = yuancheMapper.getTaskWasteCount(start, end);
        // 按元车group by "product_new_code", "yuanche_waste_count"
        Map<String, Integer> yuancheWasteMap = new HashMap<>();


        for(Map<String, Object> taskWasteMap : taskWasteList){
            String product_new_code = (String) taskWasteMap.get("product_new_code");
            Integer waste = ((BigDecimal) taskWasteMap.get("sum_waste_amount")).intValue();


            // 已存在，拿出来更新值
            if(yuancheWasteMap.get(product_new_code)!=null){
                waste = waste + yuancheWasteMap.get(product_new_code);
            }

            yuancheWasteMap.put(product_new_code,waste);
        }


        return yuancheWasteMap;
    }*/

    @Override
    public Map<String, Integer> getChuqiCount(int lastMouth) throws Exception{
        /**
         *     select  product_new_code, sum(amount) sum_last_amount
         *     from smart_process_task
         *     where end_date between #{start} and #{end}
         *     group by product_new_code
         */

        SmartProcessTaskExample sptExample = new SmartProcessTaskExample();
        SmartProcessTaskExample.Criteria sptCriteria = sptExample.createCriteria();

//        smartProcessTaskMapper.selectByExample(example);

        /*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start = sdf.parse("2019-01-01 00:00:00");
        Date end = sdf.parse("2019-01-31 23:59:59");
        Date save_start = sdf.parse("2019-01-01 00:00:00");
        Date save_end = sdf.parse("2019-01-31 23:59:59");
        Date end_start = sdf.parse("2019-02-01 00:00:00");
        Date end_end = sdf.parse("2019-02-30 23:59:59");

        // 计算主齿元车上月累计完成数
        List<Map<String, Object>> yuancheCount = yuancheMapper.getYuancheCount(start, end);
        // 计算主齿元车上月的本月完成数
        List<Map<String, Object>> yuancheThisCount = yuancheMapper.getYuancheThisCount(save_start, save_end, end_start, end_end);
        // 计算上月的主齿钳工废次品总数
        Map<String, Integer> yuancheWasteCount = this.getYuancheWasteCount(start, end);
        // 1. 主齿元车期初数：步骤1 – 步骤2 – 步骤3*/


        return null;
    }

    @Autowired
    private SmartProductMapper smartProductMapper;

    @Override
    public PageInfo<YuancheDto> getYuancheList(PageQuery<YuancheQuery> yuanchePageQueryVo) {

        YuancheQuery yuancheQuery = yuanchePageQueryVo.getQueryItem();

        // 完成时间
        String finishMonth = yuancheQuery.getFinishMonth();
        int year = Integer.parseInt(finishMonth.split("-")[0]);
        int mouth = Integer.parseInt(finishMonth.split("-")[1]);
        Date thisMouthStart = DateUtils.getMonthStart(year, mouth+1);
        Date thisMouthEnd = DateUtils.getMonthEnd(year, mouth+1);
        Date lastMouthStart = DateUtils.getMonthStart(year, mouth);
        Date lastMouthEnd = DateUtils.getMonthEnd(year, mouth);



        // 分页
        PageHelper.startPage(yuanchePageQueryVo.getPage(), yuanchePageQueryVo.getLimit());

        SmartProductExample spExample = new SmartProductExample();
        SmartProductExample.Criteria spCriteria = spExample.createCriteria();

        // 筛选条件
        if(!StringUtils.isEmpty(yuancheQuery.getCode())){
            spCriteria.andCodeEqualTo(yuancheQuery.getCode());
        }
        if(!StringUtils.isEmpty(yuancheQuery.getOldCode())){
            spCriteria.andOldCodeEqualTo(yuancheQuery.getOldCode());
        }
        if(!StringUtils.isEmpty(yuancheQuery.getWorkpieceCode())){
            spCriteria.andWorkpieceCodeEqualTo(yuancheQuery.getWorkpieceCode());
        }

        // TODO 批次号加入筛选条件  yuancheQuery.getPch()


        List<SmartProduct> smartProducts = smartProductMapper.selectByExample(spExample);
        // 分页信息
        PageInfo pageInfo = new PageInfo<>(smartProducts);

        // 整理YuancheDto （复制属性
        List<YuancheDto> yuancheDtoList = new ArrayList<>();
        for(SmartProduct smartProduct : smartProducts){

            // 成品件号、老编码、工件型号编码
            YuancheDto yuancheDto = new YuancheDto();
            yuancheDto.setCode(smartProduct.getCode());
            yuancheDto.setOldCode(smartProduct.getOldCode());
            yuancheDto.setWorkpieceCode(smartProduct.getWorkpieceCode());

            // TODO 批次号


            // 单行统计数据时的筛选条件
            YuancheVo yuancheVo = new YuancheVo();
            yuancheVo.setProductNewCode(smartProduct.getCode());
            // TODO 不变条件 抽取到for外面
            yuancheVo.setThisMouthStart(thisMouthStart);
            yuancheVo.setThisMouthEnd(thisMouthEnd);
            yuancheVo.setLastMouthStart(lastMouthStart);
            yuancheVo.setLastMouthEnd(lastMouthEnd);

            // 初期数
            // 1- 计算主齿元车上月累计完成数
            Integer lastCount = yuancheMapper.getYuancheCount(yuancheVo);
            // 2- 计算主齿元车上月的本月完成数
            Integer thisCount = yuancheMapper.getYuancheThisCount(yuancheVo);
            // 3- 计算上月的主齿钳工废次品总数
            Integer wasteCount = yuancheMapper.getYuancheWasteCount(yuancheVo);
            // 主齿元车期初数：步骤1 – 步骤2 – 步骤3
            Integer cqs = lastCount-thisCount-wasteCount;
            yuancheDto.setCqs(cqs);


            // 主齿元车完成数量 dailyFinish
            List<Map<String, Object>> dailyCounts = yuancheMapper.getDailyCount(yuancheVo);
            List<Map<String, Object>> dailyWasteCounts = yuancheMapper.getDailyWasteCount(yuancheVo);
            Integer[] dailyFinish = new Integer[31];

            int mouthFinish = 0;    // 本月完成数
            int dayCount;
            int dayWasteCount;
            for(int i=1; i<=31; ++i){
                dayCount = this.getCountByDay(dailyCounts, i);
                dayWasteCount = this.getCountByDay(dailyWasteCounts, i);
                int dayFinish = dayCount - dayWasteCount;
                dailyFinish[i-1] = dayFinish;
                mouthFinish += dayFinish;

            }
            yuancheDto.setDailyFinish(dailyFinish);

            // 本月完成
            yuancheDto.setMonthFinish(mouthFinish);

            // 累计完成 = 初期数 + 本月完成
            int totalFinish = cqs + mouthFinish;
            yuancheDto.setTotalFinish(totalFinish);

            yuancheDtoList.add(yuancheDto);
        }

        // 封装（ 修改list
        pageInfo.setList(yuancheDtoList);
//        PageInfo<YuancheDto> pageInfo = new PageInfo<>(yuancheDtoList);

//        new PageInfo<>()
        return pageInfo;
    }

    /**
     * 根据day(1-31) 找对应的 counts
     * @return
     */
    private int getCountByDay(List<Map<String, Object>> counts, int day){
        int dayCount = 0;
        for(Map<String, Object> dailyCount: counts){
            // 将日期格式转化为1-31的数字
            Date dayDate = (Date) dailyCount.get("dayDate");
            int mouthDay = DateUtils.getMouthDay(dayDate);
            if(mouthDay == day){
                dayCount = ((BigDecimal)dailyCount.get("mCount")).intValue();
                break;
            }
        }

        return dayCount;
    }


}
